package net.xiaosaguo.mymall.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.xiaosaguo.common.utils.HttpUtils;
import net.xiaosaguo.common.utils.PageUtils;
import net.xiaosaguo.common.utils.Query;
import net.xiaosaguo.mymall.member.dao.MemberDao;
import net.xiaosaguo.mymall.member.entity.MemberEntity;
import net.xiaosaguo.mymall.member.exception.PhoneExistException;
import net.xiaosaguo.mymall.member.exception.UniqueCheckFailureException;
import net.xiaosaguo.mymall.member.exception.UsernameExistException;
import net.xiaosaguo.mymall.member.service.MemberLevelService;
import net.xiaosaguo.mymall.member.service.MemberService;
import net.xiaosaguo.mymall.member.vo.MemberLoginVO;
import net.xiaosaguo.mymall.member.vo.MemberRegisterVO;
import net.xiaosaguo.mymall.member.vo.WeiboSocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVO vo) {
        MemberEntity memberEntity = new MemberEntity();

        // 检查唯一性
        // 为了让 controller 能感知到异常，异常机制
        checkUsernameUnique(vo.getUsername());
        checkPhoneUnique(vo.getPhone());
        memberEntity.setUsername(vo.getUsername());
        memberEntity.setMobile(vo.getPhone());

        // 密码加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        memberEntity.setPassword(passwordEncoder.encode(vo.getPassword()));

        // 其他默认信息
        // 设置默认等级
        memberEntity.setLevelId(memberLevelService.getDefaultLevel());
        memberEntity.setCreateTime(new Date());
        memberEntity.setNickname(vo.getUsername());

        this.save(memberEntity);
    }

    @Override
    public void checkEmailUnique(String email) throws UniqueCheckFailureException {
        Integer count = this.lambdaQuery().eq(MemberEntity::getEmail, email).count();
        if (count > 0) {
            throw new UniqueCheckFailureException("邮箱已存在");
        }
    }

    @Override
    public void checkUsernameUnique(String username) throws UsernameExistException {
        Integer count = this.lambdaQuery().eq(MemberEntity::getUsername, username).count();
        if (count > 0) {
            throw new UsernameExistException();
        }
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException {
        Integer count = this.lambdaQuery().eq(MemberEntity::getMobile, phone).count();
        if (count > 0) {
            throw new PhoneExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVO vo) {

        // 去数据库中查询用户
        MemberEntity member = this.lambdaQuery()
                .eq(MemberEntity::getUsername, vo.getLoginacct())
                .or()
                .eq(MemberEntity::getMobile, vo.getLoginacct())
                .one();
        if (member == null) {
            return null;
        } else {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean matches = passwordEncoder.matches(vo.getPassword(), member.getPassword());
            if (matches) {
                return member;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(WeiboSocialUser vo) {
        // 具有登录和注册合并逻辑
        String uid = vo.getUid();
        // 1. 判断当前社交用户是否已经登录过系统
        MemberEntity member = this.lambdaQuery().eq(MemberEntity::getSocialUid, uid).one();
        if (member != null) {
            // 更新令牌
            MemberEntity updater = new MemberEntity();
            updater.setId(member.getId());
            updater.setAccessToken(vo.getAccessToken());
            updater.setExpiresIn(vo.getExpiresIn());
            this.updateById(updater);
            // 登录
            member.setAccessToken(vo.getAccessToken());
            member.setExpiresIn(vo.getExpiresIn());
            return member;
        } else {
            // 注册
            MemberEntity register = new MemberEntity();

            try {
                // 社交资料 根据令牌，查出当前用户的社交资料（昵称、性别等）
                // https://api.weibo.com/2/users/show.json
                Map<String, String> map = new HashMap<>(8);
                map.put("access_token", vo.getAccessToken());
                map.put("uid", vo.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json",
                        "get", new HashMap<>(0), map);
                if (response.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
                    String entityStr = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(entityStr);
                    String nickname = jsonObject.getString("name");
                    String gender = jsonObject.getString("gender");
                    String profileImageUrl = jsonObject.getString("profile_image_url");
                    register.setNickname(nickname);
                    register.setGender("m".equals(gender) ? 1 : 0);
                    register.setHeader(profileImageUrl);
                }
            } catch (Exception ignored) {
            }

            // 设置默认等级
            register.setLevelId(memberLevelService.getDefaultLevel());
            register.setCreateTime(new Date());

            // 社交账号信息
            register.setSocialUid(vo.getUid());
            register.setAccessToken(vo.getAccessToken());
            register.setExpiresIn(vo.getExpiresIn());
            this.save(register);
            return register;
        }
    }

}